var koa           = require('koa');
var views         = require('co-views');
var path          = require('path');
var config        = require('./config');
var middlewares   = require('koa-middlewares');

var app           = new koa();
var render        = views(__dirname + '/views', {
      map: { html: "ejs" }
    });

app.use(middlewares.favicon());
app.use(middlewares.rt());
// console.log(process.env);
/**
 * static file server
 */
// ['public','node_modules'].forEach(function (ele,idx) {
['public'].forEach(function (ele,idx) {

  app.use(middlewares.staticCache(path.join(__dirname, ele), {
    buffer: !config.debug,
    maxAge: config.debug ? 0 : 60 * 60 * 24 * 7
  }));
});
// app.use(middlewares.bodyParser());

// if (config.debug && process.env.NODE_ENV !== 'test') {
//   app.use(middlewares.logger());
// }

// x-response-time
// app.use(function *(next){
//   console.log(this.request.type+'---');
//   var start = new Date;
//   yield next;//
//   var ms = new Date - start;
//   this.set('X-Response-Time', ms + 'ms');
//   console.log('Response');
// });
//
// logger

app.use(function *(next){
  var start = new Date;
  yield next;
  var ms = new Date - start;
  console.log('%s %s - %s', this.method, this.url, ms);
});
var router        = require('./route')(render);
// response
app.use(router.routes());
app.locals = {
  title:'AAA'
}
// app.use(function *(){
//   console.log(this.request.originalUrl);
//   var index = yield render('index', {});
//   this.body = yield render('layout', {  body: index });
//     // console.log(html);
//
//   // this.body = yield render('index', { });
//   // this.body = 'DX3906 Star , a place where is building !';
// });
// 错误处理
app.on('error', function(err){
  log.error('server error', err);
});
app.listen(config.port,function () {
  console.log('Server started ! please visit at : "localhost:'+config.port+'"');
})
